<template>
  <div class="mobile-home">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="header-title">H+移动工作平台</div>
      <div class="header-right" @click="showMessages = true">
        <van-badge :content="unreadCount || ''" max="99">
          <van-icon name="bell" size="24" />
        </van-badge>
      </div>
    </div>
    
    <!-- 搜索栏 -->
    <div class="search-bar">
      <van-search
        v-model="keyword"
        placeholder="搜索功能、文档、物资..."
        shape="round"
        background="#ffffff"
        @focus="onSearchFocus"
      />
    </div>
    
    <!-- 通知中心 -->
    <div class="message-section">
      <div class="section-header">
        <div class="section-title">
          <van-icon name="comment" color="#1A7BB9" />
          <span>统一消息中心</span>
        </div>
        <div class="section-more" @click="viewAllMessages">查看全部</div>
      </div>
      
      <van-tabs v-model:active="activeTab" swipeable animated>
        <van-tab title="待办">
          <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
            <div class="message-list">
              <div class="empty-tip" v-if="todoList.length === 0">
                <van-empty description="暂无待办事项" />
              </div>
              <van-cell v-for="item in todoList" :key="item.id" clickable @click="handleTodoItem(item)">
                <template #icon>
                  <div class="message-icon" :class="item.status">
                    <van-icon :name="getIconByStatus(item.status)" />
                  </div>
                </template>
                <template #title>
                  <div class="message-title">{{item.title}}</div>
                </template>
                <template #default>
                  <div class="message-content">{{item.content}}</div>
                  <div class="message-time">{{item.time}}</div>
                </template>
              </van-cell>
            </div>
          </van-pull-refresh>
        </van-tab>
        <van-tab title="流程">
          <div class="message-list">
            <van-empty description="暂无流程消息" />
          </div>
        </van-tab>
        <van-tab title="通知">
          <div class="message-list">
            <van-empty description="暂无通知消息" />
          </div>
        </van-tab>
        <van-tab title="公告">
          <div class="message-list">
            <van-empty description="暂无公告消息" />
          </div>
        </van-tab>
      </van-tabs>
    </div>
    
    <!-- 常用功能 -->
    <div class="function-section">
      <div class="section-header">
        <div class="section-title">
          <van-icon name="star" color="#1A7BB9" />
          <span>常用功能</span>
        </div>
        <div class="section-more" @click="editFunctions">
          {{ isEditing ? '完成' : '编辑' }}
        </div>
      </div>
      
      <div class="function-grid">
        <draggable 
          v-model="functionList" 
          item-key="id"
          :disabled="!isEditing"
          animation="300"
          :delay="50"
          @end="saveFunctionOrder"
          class="draggable-container"
        >
          <template #item="{ element }">
            <div class="function-item" @click="!isEditing ? navigateTo(element.path) : null">
              <div class="function-icon" :class="element.iconBg">
                <van-icon :name="element.icon" size="24" />
                <div class="edit-overlay" v-if="isEditing">
                  <van-icon class="visibility-toggle" :name="element.hidden ? 'eye-o' : 'eye'" size="18" @click.stop="toggleFunctionVisibility(element)"/>
                  <van-icon class="remove-icon" name="cross" size="16" @click.stop="removeCommonFunction(element.id)" />
                </div>
              </div>
              <div class="function-name">{{ element.name }}</div>
            </div>
          </template>
        </draggable>
      </div>
    </div>
    
    <!-- 最近访问 -->
    <div class="recent-section">
      <div class="section-header">
        <div class="section-title">
          <van-icon name="clock" color="#1A7BB9" />
          <span>最近访问</span>
        </div>
        <div class="section-more" @click="clearRecent">清空</div>
      </div>
      
      <div class="recent-list">
        <div class="empty-tip" v-if="recentList.length === 0">
          <van-empty description="暂无访问记录" />
        </div>
        <van-cell 
          v-for="item in recentList" 
          :key="item.id" 
          clickable 
          @click="navigateTo(item.path)"
        >
          <template #icon>
            <div class="recent-icon" :class="item.iconBg">
              <van-icon :name="item.icon" size="20" />
            </div>
          </template>
          <template #title>
            <div class="recent-title">{{item.name}}</div>
          </template>
          <template #default>
            <div class="recent-time">{{item.time}}</div>
            <van-icon name="arrow" />
          </template>
        </van-cell>
      </div>
    </div>
    
    <!-- 底部导航栏 -->
    <van-tabbar v-model="activeTabbar" route>
      <van-tabbar-item name="home" icon="home-o" to="/new/home">首页</van-tabbar-item>
      <van-tabbar-item name="apps" icon="apps-o" to="/new/apps">应用</van-tabbar-item>
      <van-tabbar-item name="profile" icon="user-o" to="/new/profile">我的</van-tabbar-item>
    </van-tabbar>
    
    <!-- 消息抽屉 -->
    <van-popup
      v-model:show="showMessages"
      position="right"
      :style="{ width: '85%', height: '100%' }"
    >
      <div class="message-drawer">
        <van-nav-bar
          title="消息中心"
          left-arrow
          @click-left="showMessages = false"
        />
        <van-tabs v-model:active="drawerActiveTab">
          <van-tab title="全部">
            <van-list>
              <van-cell v-for="item in allMessages" :key="item.id">
                <template #icon>
                  <div class="message-icon" :class="item.status">
                    <van-icon :name="getIconByStatus(item.status)" />
                  </div>
                </template>
                <template #title>
                  <div class="message-title">{{item.title}}</div>
                </template>
                <template #default>
                  <div class="message-content">{{item.content}}</div>
                  <div class="message-time">{{item.time}}</div>
                </template>
              </van-cell>
            </van-list>
          </van-tab>
          <van-tab title="未读">
            <van-empty description="暂无未读消息" />
          </van-tab>
        </van-tabs>
      </div>
    </van-popup>
    
    <!-- 搜索抽屉 -->
    <van-popup
      v-model:show="showSearch"
      position="right"
      :style="{ width: '100%', height: '100%' }"
    >
      <div class="search-drawer">
        <van-search
          v-model="keyword"
          placeholder="搜索功能、文档、物资..."
          show-action
          @cancel="showSearch = false"
          @search="onSearch"
        />
        <div class="search-results">
          <template v-if="keyword && hasSearchResults">
            <van-cell-group title="搜索结果">
              <van-cell 
                v-for="item in searchResults" 
                :key="item.id"
                :title="item.name"
                :label="item.description"
                :icon="item.icon || 'search'"
                clickable
                @click="navigateTo(item.path)"
              />
            </van-cell-group>
          </template>
          
          <van-empty description="暂无搜索结果" v-else-if="keyword && !hasSearchResults" />
          
          <template v-else>
            <!-- 搜索历史 -->
            <van-cell-group v-if="searchHistory.length > 0">
              <div class="search-history-header">
                <div class="search-history-title">搜索历史</div>
                <van-icon name="delete" @click="clearSearchHistory" />
              </div>
              <div class="search-history-tags">
                <van-tag 
                  v-for="(term, index) in searchHistory" 
                  :key="index"
                  plain 
                  round 
                  size="medium"
                  @click="keyword = term; onSearch()"
                >
                  {{ term }}
                </van-tag>
              </div>
            </van-cell-group>
            
            <!-- 热门搜索 -->
            <van-cell-group title="热门搜索">
              <van-cell title="报销申请" icon="balance-o" clickable @click="navigateTo('/finance/expense')" />
              <van-cell title="物资申领" icon="shopping-cart-o" clickable @click="navigateTo('/material/apply')" />
              <van-cell title="工资条" icon="gold-coin-o" clickable @click="navigateTo('/finance/salary')" />
            </van-cell-group>
          </template>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { 
  Search, Icon, Badge, Cell, CellGroup, Tab, Tabs, Empty, PullRefresh, 
  List, Popup, NavBar, Tabbar, TabbarItem, Button, Toast
} from 'vant'
import draggable from 'vuedraggable'

export default {
  name: 'MobileHome',
  components: {
    vanSearch: Search,
    vanIcon: Icon,
    vanBadge: Badge,
    vanCell: Cell,
    vanCellGroup: CellGroup,
    vanTab: Tab,
    vanTabs: Tabs,
    vanEmpty: Empty,
    vanPullRefresh: PullRefresh,
    vanList: List,
    vanPopup: Popup,
    vanNavBar: NavBar,
    vanTabbar: Tabbar,
    vanTabbarItem: TabbarItem,
    vanButton: Button,
    draggable
  },
  setup() {
    const router = useRouter()
    const store = useStore()
    
    const keyword = ref('')
    const activeTab = ref(store.state.mobile.appState.homeActiveTab || 0)
    const activeTabbar = ref('home')
    const drawerActiveTab = ref(0)
    const unreadCount = computed(() => store.getters['mobile/totalUnreadCount'])
    const refreshing = ref(false)
    const showMessages = ref(false)
    const showSearch = ref(false)
    const isEditing = ref(false)
    
    // 使用Vuex中的数据
    const functionList = computed(() => store.state.mobile.functionList)
    const recentList = computed(() => store.state.mobile.recentVisits.slice(0, 5))
    const todoList = computed(() => store.state.mobile.messageCenter.todoList)
    const searchHistory = computed(() => store.state.mobile.searchHistory)
    
    // 通过getter获取所有消息列表
    const allMessages = computed(() => {
      return [
        ...store.state.mobile.messageCenter.todoList,
        ...store.state.mobile.messageCenter.processList,
        ...store.state.mobile.messageCenter.noticeList,
        ...store.state.mobile.messageCenter.announcementList
      ]
    })
    
    // 监听标签页变化
    watch(activeTab, (newVal) => {
      store.commit('mobile/UPDATE_APP_STATE', { key: 'homeActiveTab', value: newVal })
    })
    
    // 刷新数据
    const onRefresh = async () => {
      try {
        await store.dispatch('mobile/loadMessages')
      } finally {
        refreshing.value = false
      }
    }
    
    // 处理待办项
    const handleTodoItem = (item) => {
      console.log('处理待办项:', item)
      // 根据待办项类型导航到对应页面
      if (item.path) {
        navigateTo(item.path)
      }
    }
    
    // 根据状态获取图标
    const getIconByStatus = (status) => {
      switch(status) {
        case 'pending': return 'info-o'
        case 'approved': return 'checked'
        case 'rejected': return 'close'
        case 'warning': return 'warning-o'
        default: return 'info-o'
      }
    }
    
    // 查看所有消息
    const viewAllMessages = () => {
      showMessages.value = true
    }
    
    // 编辑功能
    const editFunctions = () => {
      isEditing.value = !isEditing.value
    }
    
    // 保存功能顺序
    const saveFunctionOrder = () => {
      // The v-model on draggable already updates the store order if needed, 
      // but explicit save might be useful depending on store implementation.
      // For now, we assume draggable handles the order directly via v-model binding.
      // store.dispatch('mobile/saveFunctionOrder', functionList.value)
    }
    
    // 切换功能可见性
    const toggleFunctionVisibility = (item) => {
      store.dispatch('mobile/toggleFunctionVisibility', item.id)
    }
    
    // 清空最近访问
    const clearRecent = () => {
      store.dispatch('mobile/clearVisitHistory')
    }
    
    // 导航到指定路径
    const navigateTo = (path) => {
      router.push(path)
      
      // 记录访问历史
      const visitedRoute = router.resolve(path)
      if (visitedRoute) {
        store.dispatch('mobile/recordVisit', {
          path: path,
          name: visitedRoute.name || path.split('/').pop(),
          time: new Date().toLocaleString('zh-CN', {
            month: 'numeric',
            day: 'numeric',
            hour: 'numeric',
            minute: 'numeric'
          }),
          icon: getIconForPath(path),
          iconBg: getColorForPath(path)
        })
      }
    }
    
    // 根据路径获取图标
    const getIconForPath = (path) => {
      if (path.includes('/finance')) return 'balance-o'
      if (path.includes('/material')) return 'shopping-cart-o'
      if (path.includes('/asset')) return 'desktop-o'
      if (path.includes('/profile')) return 'user-o'
      return 'apps-o'
    }
    
    // 根据路径获取颜色
    const getColorForPath = (path) => {
      if (path.includes('/finance')) return 'blue'
      if (path.includes('/material')) return 'green'
      if (path.includes('/asset')) return 'purple'
      if (path.includes('/profile')) return 'orange'
      return 'cyan'
    }
    
    // 搜索聚焦
    const onSearchFocus = () => {
      showSearch.value = true
    }
    
    // 执行搜索
    const onSearch = async () => {
      if (!keyword.value.trim()) return
      
      const results = await store.dispatch('mobile/search', keyword.value)
      searchResults.value = results
    }
    
    // 清除搜索历史
    const clearSearchHistory = () => {
      store.dispatch('mobile/clearSearchHistory')
    }
    
    // 搜索结果
    const searchResults = ref([])
    
    // 判断是否有搜索结果
    const hasSearchResults = computed(() => {
      return searchResults.value && searchResults.value.length > 0
    })
    
    // Remove a function from common functions
    const removeCommonFunction = (id) => {
       console.log("Attempting to remove function with id:", id); 
      store.dispatch('mobile/removeFunction', id)
    }
    
    onMounted(() => {
      // 初始化数据
      store.dispatch('mobile/initData')
    })
    
    return {
      keyword,
      activeTab,
      activeTabbar,
      drawerActiveTab,
      unreadCount,
      refreshing,
      todoList,
      functionList,
      recentList,
      allMessages,
      searchResults,
      hasSearchResults,
      searchHistory,
      showMessages,
      showSearch,
      isEditing,
      onRefresh,
      handleTodoItem,
      getIconByStatus,
      viewAllMessages,
      editFunctions,
      saveFunctionOrder,
      toggleFunctionVisibility,
      clearRecent,
      navigateTo,
      onSearchFocus,
      onSearch,
      clearSearchHistory,
      removeCommonFunction
    }
  }
}
</script>

<style scoped>
.mobile-home {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 50px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 44px;
  background-color: #1A7BB9;
  color: white;
  padding: 0 16px;
}

.header-title {
  font-size: 18px;
  font-weight: 500;
}

.search-bar {
  padding: 8px 0;
  background-color: #ffffff;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
}

.section-title .van-icon {
  margin-right: 4px;
}

.section-more {
  font-size: 14px;
  color: #1A7BB9;
}

.message-section {
  margin: 12px 0;
  background-color: #ffffff;
}

.message-icon {
  width: 36px;
  height: 36px;
  border-radius: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
}

.message-icon.pending {
  background-color: #E3F2FD;
  color: #1A7BB9;
}

.message-icon.approved {
  background-color: #E8F5E9;
  color: #4CB050;
}

.message-icon.rejected {
  background-color: #FFEBEE;
  color: #E53935;
}

.message-icon.warning {
  background-color: #FFF3E0;
  color: #FF9800;
}

.message-title {
  font-size: 15px;
  font-weight: 500;
  margin-bottom: 4px;
}

.message-content {
  font-size: 13px;
  color: #546E7A;
  margin-bottom: 4px;
}

.message-time {
  font-size: 12px;
  color: #90A4AE;
}

.function-section {
  margin: 12px 0;
  background-color: #ffffff;
  padding-bottom: 16px;
}

.function-grid {
  padding: 0;
}

.draggable-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  padding: 0 16px 8px;
}

.function-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.function-icon {
  position: relative;
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
  color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.2s;
}

.function-icon:active {
  transform: scale(0.95);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.function-icon.blue { background-color: #1A7BB9; }
.function-icon.green { background-color: #4CB050; }
.function-icon.orange { background-color: #FF9800; }
.function-icon.purple { background-color: #8E24AA; }
.function-icon.cyan { background-color: #00BCD4; }
.function-icon.red { background-color: #E53935; }

.edit-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.4);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  padding: 2px;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.2s;
}

.function-item:hover .edit-overlay,
.function-icon:hover .edit-overlay {
  opacity: 1;
}

.is-editing .edit-overlay {
  opacity: 1;
}

.edit-overlay .van-icon {
  color: white;
  cursor: pointer;
}

.visibility-toggle {
  /* Example: margin-bottom: 4px; */
}

.remove-icon {
  position: absolute;
  top: -5px;
  right: -5px;
  background-color: rgba(255, 0, 0, 0.7);
  border-radius: 50%;
  padding: 2px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.function-name {
  font-size: 12px;
  color: #263238;
  text-align: center;
}

.recent-section {
  margin: 12px 0;
  background-color: #ffffff;
}

.recent-icon {
  width: 32px;
  height: 32px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  color: white;
}

.recent-icon.blue { background-color: #1A7BB9; }
.recent-icon.green { background-color: #4CB050; }
.recent-icon.orange { background-color: #FF9800; }
.recent-icon.purple { background-color: #8E24AA; }

.recent-title {
  font-size: 15px;
  font-weight: 500;
}

.recent-time {
  font-size: 12px;
  color: #90A4AE;
  margin-right: 8px;
}

.message-drawer, .search-drawer {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.message-list, .recent-list, .search-results {
  flex: 1;
  overflow-y: auto;
}

.search-history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px 0;
}

.search-history-title {
  font-size: 14px;
  color: #323233;
  font-weight: 500;
}

.search-history-tags {
  display: flex;
  flex-wrap: wrap;
  padding: 8px 12px;
  gap: 8px;
}

.search-history-tags .van-tag {
  margin-right: 0;
  cursor: pointer;
}

.empty-tip {
  padding: 24px 0;
}

.recent-section {
  margin: 12px 0;
}
</style> 